<template>
    <div>
        <slot></slot>
        <div class="context-menu" v-show="visible">
            <ul>
                <li @click.stop="handleClick(item)" v-for="(item, index) in menu" :key="index">{{ item.label }}</li>
            </ul>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        menu: {
            type: Array,
            required: true
        }
    },
    data() {
        return {
            visible: false
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.$el.addEventListener('contextmenu', this.showMenu)
        })
        window.addEventListener('click', this.closeMenu, true)
    },
    unmounted() {
        this.$el.removeEventListener('contextmenu')
    },
    methods: {
        handleClick(option) {
            this.$emit('select', option)
            this.closeMenu()
        },
        showMenu(event) {
            event.preventDefault()
            event.stopPropagation()
            const x = event.clientX
            const y = event.clientY

            this.$el.querySelector('.context-menu').style.position = 'fixed'
            this.$el.querySelector('.context-menu').style.left = `${x}px`
            this.$el.querySelector('.context-menu').style.top = `${y}px`

            this.visible = true
        },
        closeMenu() {
            this.visible = false
        }
    }
}
</script>

<style scoped>
.context-menu {
    position: fixed;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    z-index: 10000;
}
.context-menu li {
    margin: 0;
    padding: 8px 25px;
    cursor: pointer;
    font-size: 12px;
}
.context-menu li:hover {
    background: #eee;
}
</style>
